﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DevExpress.Web.ASPxEditors;

public partial class ShoppingCart : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ShowCart();
    }
    private void ShowCart()
    {
        bool b = true;
        if (Session["ShoppingCart"] != null)
        {
            DataTable dt = Session["ShoppingCart"] as DataTable;
            if (dt.Rows.Count > 0)
            {
                GridView1.DataSource = dt;

                GridView1.DataBind();
//                ASPxLabel2.EncodeHtml = false;
                ASPxLabel2.Text =
                    String.Format("Tổng số: <span style='color:red;'> {0:N0} VND</span>", (Session["ShoppingCart"] as MyShoppingCart).TotalPrice);
                b = false;
            }
        }
        if (b)
        {
            ASPxLabel1.Text = "Giỏ hàng của bạn hiện tại rỗng, hãy quay <a href='Homepage.aspx'>trở lại</a> để mua hàng";
            ASPxLabel1.EncodeHtml = false;
        }
        SetEnable(!b);
    }

    private void SetEnable(bool b)
    {
        ASPxLabel1.Visible = !b;
        ASPxLabel2.Visible = b;
        ASPxButton1.Visible = b;
        ASPxButton2.Visible = b;
        GridView1.Visible = b;
    }
    protected void ASPxButton1_Click(object sender, EventArgs e)
    {
        if(Session["ShoppingCart"] != null)
        {
            (Session["ShoppingCart"] as MyShoppingCart).RemoveAll();
        }
        Response.Redirect("ShoppingCart.aspx");
    }
    protected void ASPxButton2_Click(object sender, EventArgs e)
    {
        Response.Redirect("Order.aspx");
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        ShowCart();
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        (Session["ShoppingCart"] as MyShoppingCart).RemoveItem(e.RowIndex);
        GridView1.EditIndex = -1;
        ShowCart();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        TextBox amount = GridView1.Rows[e.RowIndex].Cells[3].FindControl("TextBox1") as TextBox;
        if(int.Parse(amount.Text) == 0)
        {
            (Session["ShoppingCart"] as MyShoppingCart).RemoveItem(e.RowIndex);
        }
        else
        {
            (Session["ShoppingCart"] as MyShoppingCart).UpdateAmount(e.RowIndex, int.Parse(amount.Text));
        }
        GridView1.EditIndex = -1;
        ShowCart();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;

        ShowCart();
    }
}
